package com.jstyle.jclife.activity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.HistoryShowAdapter;
import com.jstyle.jclife.adapter.HistoryStepWeekAdapter;
import com.jstyle.jclife.adapter.HistoryStepYearAdapter;
import com.jstyle.jclife.daoManager.StepDataDaoManager;
import com.jstyle.jclife.model.StepData;
import com.jstyle.jclife.utils.ChartDataUtil;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.ResolveData;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.Utils;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lecho.lib.hellocharts.view.ColumnChartView;

public class HistoryActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.bt_goal_back)
    Button btGoalBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.rb_history_week)
    RadioButton rbHistoryWeek;
    @BindView(R.id.rb_history_month)
    RadioButton rbHistoryMonth;
    @BindView(R.id.rb_history_year)
    RadioButton rbHistoryYear;
    @BindView(R.id.rg_history)
    RadioGroup rgHistory;
    @BindView(R.id.bt_data_month_preMonth)
    ImageView btDataMonthPreMonth;
    @BindView(R.id.bt_data_month_date)
    Button btDataMonthDate;
    @BindView(R.id.bt_data_month_nextMonth)
    ImageView btDataMonthNextMonth;
    @BindView(R.id.ColumnChartView_history)
    ColumnChartView ColumnChartViewHistory;
    @BindView(R.id.RecyclerView_history_detail)
    RecyclerView RecyclerViewHistoryDetail;
    @BindView(R.id.RecyclerView_history)
    RecyclerView RecyclerViewHistory;
    @BindView(R.id.bt_history_dataType)
    Button btHistoryDataType;
    @BindView(R.id.ll_scrollView)
    NestedScrollView llScrollView;
    @BindView(R.id.ll_child)
    LinearLayout llChild;
    private HistoryShowAdapter historyShowAdapter;
    String[] content = new String[]{"卡路里", "距离", "平均心率", "运动时长"};
    private static final String TAG = "HistoryActivity";
    public int dateType = 0;
    public final static int dateWeek = 0;
    public final static int dateMonth = 1;
    public final static int dateYear = 2;
    private String thisMonth;
    private String[] monthDates;
    private String[] thisWeek;
    int year;
    private int[] stepsCount = new int[]{4, 4, 3};
    private int[] otherCount = new int[]{3, 3, 2};
    @BindString(R.string.day_avg)
    String dayAvg;
    @BindString(R.string.month_avg)
    String monthAvg;
    @BindString(R.string.week_avg)
    String weekAvg;
    @BindString(R.string.goal_finish_days)
    String goalFinishDays;
    @BindString(R.string.total_steps)
    String totalSteps;
    @BindString(R.string.total_distance)
    String totalDistance;
    @BindString(R.string.total_exercise_time)
    String totalSExerciseTime;
    @BindString(R.string.total_sport_time)
    String totalSportTime;
    @BindString(R.string.total_sport_cal)
    String totalCal;
    private int DATA_TYPE = 0;
    public final static int DATA_STEPS = 0;
    public final static int DATA_CAL = 1;
    public final static int DATA_DISTANCE = 2;
    public final static int DATA_EXERCISE_TIME = 3;
    public final static int DATA_SPORT_TIME = 4;
    public static final String KEY_DATA_TYPE = "DATA_TYPE";

    private String title;
    List<StepData> stepDataList = new ArrayList<>();
    @BindArray(R.array.week_chartstep)
    String[] weekString;
    String label = "";
    NumberFormat numberFormat;
    private Typeface mFace;
    private DividerItemDecoration dividerItemDecoration;

    // private String todayString;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_sport);
        ButterKnife.bind(this);
        mFace = Typeface.createFromAsset(getAssets(), "ROBOTO-REGULAR_2.TTF");

        initData();
        init();

    }

    private void initChartView(Map<String, Float> maps, String[] dates, float max) {
       // if (max < 0.1) max = 0;
        if(max<1&&max!=0)max=1;
        ChartDataUtil.initDataChartView(ColumnChartViewHistory, -0.3f, max * 1.2f, dates.length, 0);
        ColumnChartViewHistory.setColumnChartData(ChartDataUtil.getStepHistoryColumnChart(maps, dates, weekString, max, DATA_TYPE, mFace));
    }

//    private float getChartMax(float max) {
//        int maxData = 0;
//        switch (DATA_TYPE) {
//            case DATA_CAL:
//                String distanceCal = String.valueOf((int) max);
//                int lengthCal = distanceCal.length();
//                if (lengthCal < 2) lengthCal = 2;
//                double countCal = Math.pow(10, lengthCal - 1);
//                int resultCal = (int) (max / countCal);
//                if (resultCal < 5) {
//                    maxData = (int) (5 * countCal);
//                } else {
//                    maxData = (int) (10 * countCal);
//                }
//                break;
//            case DATA_DISTANCE:
//                float distance = max * 1000;
//                String distanceS = String.valueOf((int) distance);
//                int length = distanceS.length();
//                if (length < 3) length = 3;
//                double count = Math.pow(10, length - 1);
//                int result = (int) (distance / count);
//                if (result < 5) {
//                    maxData = (int) (5 * count);
//                } else {
//                    maxData = (int) (10 * count);
//                }
//                break;
//            case DATA_STEPS:
//                String distanceStep = String.valueOf((int) max);
//                int lengthStep = distanceStep.length();
//                if (lengthStep < 3) lengthStep = 3;
//                double countStep = Math.pow(10, lengthStep - 1);
//                int resultStep = (int) (max / countStep);
//                if (resultStep < 5) {
//                    maxData = (int) (5 * countStep);
//                } else {
//                    maxData = (int) (10 * countStep);
//                }
//                break;
//            case DATA_SPORT_TIME:
//            case DATA_EXERCISE_TIME:
//                String distanceTime = String.valueOf((int) max);
//                int lengthTime = distanceTime.length();
//                if (lengthTime < 1) lengthTime = 1;
//                double countTime = Math.pow(10, lengthTime - 1);
//                int resultTime = (int) (max / countTime);
//                if (resultTime < 5) {
//                    maxData = (int) (5 * countTime);
//                } else {
//                    maxData = (int) (10 * countTime);
//                }
//                break;
//        }
//        return maxData;
//
//
//    }

    private void initChartViewMonth(Map<String, Float> maps, String[] dates, float max) {
        if (max < 0.1f) max = 0;
        ChartDataUtil.initDataChartView(ColumnChartViewHistory, -0.5f, max * 1.2f, dates.length, 0);
        ColumnChartViewHistory.setColumnChartData(ChartDataUtil.getStepHistoryMonthColumnChart(maps, dates, max, DATA_TYPE));
    }

    private void initChartViewYear(float[] datas) {
        float max = 0;
        for (float data : datas) {
            max = Math.max(max, data);
        }
        if (max < 0.1f) max = 0;
        ChartDataUtil.initDataChartView(ColumnChartViewHistory, -0.5f, max * 1.2f, 12.5f, 0);
        ColumnChartViewHistory.setColumnChartData(ChartDataUtil.getStepHistoryYearColumnChart(datas, max, DATA_TYPE));
    }

    private void initData() {
        numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setGroupingUsed(false);
        DATA_TYPE = getIntent().getIntExtra(KEY_DATA_TYPE, DATA_STEPS);
        thisMonth = DateUtil.getMonthString("", DateUtil.this_month);
        monthDates = DateUtil.getThisMonth();
        thisWeek = DateUtil.getTodayWeek(0);
        year = Calendar.getInstance().get(Calendar.YEAR);
        getDataString();
        //todayString = DateUtil.getDefaultFormatTime(new Date());
    }

    private void init() {
        btGoalBack.setText(title);
        ScreenUtils.setTitleTypeface(btGoalBack);
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
        historyShowAdapter = new HistoryShowAdapter(listContent);
        RecyclerViewHistoryDetail.setAdapter(historyShowAdapter);
        RecyclerViewHistoryDetail.setLayoutManager(layoutManager);
        rgHistory.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_history_week:
                        dateType = dateWeek;
                        break;
                    case R.id.rb_history_month:
                        dateType = dateMonth;
                        break;
                    case R.id.rb_history_year:
                        dateType = dateYear;
                        break;
                }
                showDate();
                changeData();
            }
        });
        showDate();
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }

    @OnClick({R.id.iv_share, R.id.bt_data_month_preMonth, R.id.bt_data_month_nextMonth})
    public void onViewClicked(View view) {
        if(Utils.isFastClick()){return;}
        switch (view.getId()) {
            case R.id.iv_share:

                ScreenUtils.shareFile(this, llScrollView);
                break;
            case R.id.bt_data_month_preMonth:
                showPreDate();
                break;
            case R.id.bt_data_month_nextMonth:
                showNextDate();
                break;
        }
    }

    /**
     * 上周，月，年
     */
    private void showPreDate() {
        switch (dateType) {
            case dateWeek:
                thisWeek = DateUtil.getWeekString(thisWeek[0], DateUtil.lastWeek);
                break;
            case dateMonth:
                thisMonth = DateUtil.getMonthString(thisMonth, DateUtil.last_month);
                monthDates = DateUtil.getLastMonth(monthDates[0]);
                break;
            case dateYear:
                year--;
                break;
        }
        showDate();
    }

    /**
     * 下周，月，年
     */
    private void showNextDate() {
        switch (dateType) {
            case dateWeek:
                thisWeek = DateUtil.getWeekString(thisWeek[6], DateUtil.nextWeek);

                break;
            case dateMonth:
                thisMonth = DateUtil.getMonthString(thisMonth, DateUtil.next_month);
                monthDates = DateUtil.getNextMonth(monthDates[0]);
                break;
            case dateYear:
                year++;
                break;
        }
        showDate();
    }

    private void showDate() {
        String showDate = "";
        String startDate = null;
        String endDate = null;
        String dataSting = "";
        Calendar calendar = Calendar.getInstance();
        switch (dateType) {
            case dateWeek:
                showDate = DateUtil.getShowWeekDate(this, thisWeek[0]) + "-" + DateUtil.getShowWeekDate(this, thisWeek[6]);
                startDate = thisWeek[0];
                endDate = thisWeek[6];
                dataSting = getString(R.string.Week);
                String nowDate = DateUtil.getDefaultFormatTime(new Date());
                btDataMonthNextMonth.setEnabled(true);
                for (int i = 0; i < thisWeek.length - 1; i++) {
                    if (thisWeek[i].equals(nowDate)) {
                        btDataMonthNextMonth.setEnabled(false);
                    }
                }
                break;
            case dateMonth:
                showDate = DateUtil.getShowMonthDate(this, monthDates[0]);
                startDate = monthDates[0];
                endDate = monthDates[monthDates.length - 1];
                DateUtil.monthEnable(this, showDate);

                btDataMonthNextMonth.setEnabled(DateUtil.monthEnable(this, showDate));
                dataSting = getString(R.string.Month);
                break;
            case dateYear:
                showDate = String.valueOf(year);
                startDate = showDate.substring(2, 4) + ".01.01";
                endDate = showDate.substring(2, 4) + ".12.31";
                dataSting = getString(R.string.Year);
                int thisYear = calendar.get(Calendar.YEAR);
                btDataMonthNextMonth.setEnabled(year != thisYear);
                break;
        }
        btHistoryDataType.setText(dataSting);
        btDataMonthDate.setText(showDate);
        findStepData(startDate, endDate);
    }

    /**
     * 根据日期查找运动总数据
     *
     * @param startDate
     * @param endDate
     */
    private void findStepData(String startDate, String endDate) {
        stepDataList = StepDataDaoManager.queryData(startDate, endDate);
        Map<String, Float> map = new HashMap<>();
        float[] yearData = new float[12];
        float totalStep = 0;
        int goalDays = 0;
        float max = 0;
        for (StepData stepData : stepDataList) {
            String date = stepData.getDate();
            float step = getShowData(stepData);
            max = Math.max(max, step);
            // Log.i(TAG, "findStepData: " + date + " " + step);
            int goal = Integer.parseInt(stepData.getGoal());
            if (goal >= 100) goalDays++;
            if (step != 0) {//步数为0也有数据上传？
                map.put(date, step);
                String month = date.substring(3, 5);
                yearData[Integer.valueOf(month) - 1] += step;
            }
            totalStep += step;
        }
        Log.i(TAG, "findStepData: max" + max);
        switch (dateType) {
            case dateWeek:
                initChartView(map, thisWeek, max);
                initDetailRecycleView(map.size(), totalStep, goalDays);
                initDateRecycleView();
                break;
            case dateMonth:
                initChartViewMonth(map, monthDates, max);
                initDetailRecycleViewMonth(map.size(), totalStep, goalDays);
                initDateRecycleView();
                break;
            case dateYear:
                initChartViewYear(yearData);
                initDetailRecycleViewYear(yearData, map.size(), totalStep, goalDays);
                initDateYearRecycleView(yearData);
                break;
        }
    }

    private void initDateYearRecycleView(float[] data) {
        List<StepData> stepDataList = new ArrayList<>();
        for (int i = 0; i < data.length; i++) {
            if (data[i] != 0) {
                StepData stepData = new StepData();
                String time = year + String.format(".%02d", i + 1);
                stepData.setDate(DateUtil.getShowYearDate(this, time));
                stepData.setStep(data[i] + "");
                stepData.setShowLabel(label);
                stepDataList.add(stepData);
            }
        }
        final String format = getString(R.string.date_showFormat_month);
        Collections.sort(stepDataList, new Comparator<StepData>() {
            @Override
            public int compare(StepData o1, StepData o2) {
                Date date = DateUtil.String2Date(o1.getDate(), format);
                Date date2 = DateUtil.String2Date(o2.getDate(), format);
                return date.before(date2) ? 1 : -1;
            }
        });
        HistoryStepYearAdapter historyStepWeekAdapter = new HistoryStepYearAdapter(stepDataList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewHistory.setLayoutManager(linearLayoutManager);
        RecyclerViewHistory.setAdapter(historyStepWeekAdapter);
    }

    private void initDateRecycleView() {
        HistoryStepWeekAdapter historyStepWeekAdapter = new HistoryStepWeekAdapter(stepDataList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
     //   RecyclerViewHistory.setNestedScrollingEnabled(false);
        RecyclerViewHistory.setLayoutManager(linearLayoutManager);
        if(dividerItemDecoration==null){
            dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
            ColorDrawable colorDrawable = new ColorDrawable();
            colorDrawable.setColor(Color.DKGRAY);
            dividerItemDecoration.setDrawable(colorDrawable);
            RecyclerViewHistory.addItemDecoration(dividerItemDecoration);
        }

        List<StepData> removeList = new ArrayList<>();
        for (StepData stepData : stepDataList) {
            float data = getShowData(stepData);
            // Log.i(TAG, "initDateRecycleView: "+data);
            if (data < 0.05) removeList.add(stepData);
            if (DATA_TYPE != DATA_STEPS) {
                stepData.setDate(DateUtil.getShowDay(this, stepData.getDate()));
                stepData.setStep(String.valueOf(data));
                stepData.setShowLabel(label);
            }

        }
        stepDataList.removeAll(removeList);
        if (DATA_TYPE == DATA_STEPS) {
            RecyclerViewHistory.setAdapter(historyStepWeekAdapter);
        } else {
            HistoryStepYearAdapter historyWeekAdapter = new HistoryStepYearAdapter(stepDataList);
            RecyclerViewHistory.setAdapter(historyWeekAdapter);
        }

    }

    private void initDetailRecycleViewMonth(int size, float totalStep, int goalDays) {
        float avg = size == 0 ? 0 : totalStep / size;
        List<String> list = new ArrayList<>();
        list.add(numberFormat.format(avg) + label);
        list.add(numberFormat.format(totalStep / 4) + label);
        list.add(numberFormat.format(totalStep) + label);
        list.add(goalDays + "");
        historyShowAdapter.setStepData(list);
    }

    private void initDetailRecycleViewYear(float[] data, int size, float totalStep, int goalDays) {
        float avg = size == 0 ? 0 : totalStep / size;
        int count = 0;
        for (int i = 0; i < data.length; i++) {
            if (data[i] != 0) count++;
        }
        float monthAvg = count == 0 ? 0 : totalStep / count;
        List<String> list = new ArrayList<>();
        list.add(numberFormat.format(avg) + label);
        list.add(numberFormat.format(monthAvg) + label);
        list.add(numberFormat.format(totalStep) + label);
        list.add(goalDays + "");
        historyShowAdapter.setStepData(list);
    }

    private void initDetailRecycleView(int size, float totalStep, int goalDays) {
        Log.i(TAG, "initDetailRecycleView: " + size);
        float avg = size == 0 ? 0 : totalStep / size;
        List<String> list = new ArrayList<>();
        list.add(numberFormat.format(avg) + label);
        list.add(numberFormat.format(totalStep) + label);
        list.add(goalDays + "");
        historyShowAdapter.setStepData(list);
    }


    List<String> listContent = new ArrayList<>();

    private void changeData() {

        getDataString();
        historyShowAdapter.setData(listContent);
    }

    /**
     * RecyclerViewHistoryDetail item 下方标题
     */
    private void getDataString() {
        listContent = new ArrayList<>();
        listContent.add(dayAvg);
        switch (dateType) {
            case dateWeek:
                break;
            case dateMonth:
                listContent.add(weekAvg);
                break;
            case dateYear:
                listContent.add(monthAvg);
                break;
        }
        switch (DATA_TYPE) {
            case DATA_CAL:
                listContent.add(totalCal);
                title = getString(R.string.Calories);
                break;
            case DATA_DISTANCE:
                listContent.add(totalDistance);
                title = getString(R.string.Distance);
                break;
            case DATA_STEPS:
                listContent.add(totalSteps);
                listContent.add(goalFinishDays);
                title = getString(R.string.Steps);
                break;
            case DATA_SPORT_TIME:
                listContent.add(totalSportTime);
                title = getString(R.string.Active_Minutes);
                break;
            case DATA_EXERCISE_TIME:
                title = getString(R.string.Exercise_Minutes);
                listContent.add(totalSExerciseTime);
                break;
        }

    }

    private float getShowData(StepData stepData) {
        String data = "";
        switch (DATA_TYPE) {
            case DATA_CAL:
                data = stepData.getCal();
                label = " kcal";
                numberFormat.setMaximumFractionDigits(1);
                break;
            case DATA_DISTANCE:
                data = ResolveData.getShowDistance(stepData.getDistance());
                numberFormat.setMaximumFractionDigits(1);
                label = ResolveData.getDistanceLabel();
                break;
            case DATA_STEPS:
                data = stepData.getStep();
                numberFormat.setMaximumFractionDigits(0);
                break;
            case DATA_SPORT_TIME:
                if (!TextUtils.isEmpty(stepData.getTime())) {
                    int second = Integer.valueOf(stepData.getTime());
                    int min = second;
                    data = String.valueOf(min);
                    numberFormat.setMaximumFractionDigits(0);
                } else {
                    data = "0";
                }

                label = getString(R.string.min_label);
                break;
            case DATA_EXERCISE_TIME:
                if (!TextUtils.isEmpty(stepData.getExerciseTime())) {
                    int secondExercise = Integer.valueOf(stepData.getExerciseTime());

                    data = String.valueOf(secondExercise);
                } else {
                    data = "0";
                }
                numberFormat.setMaximumFractionDigits(0);
                label = getString(R.string.min_label);
                break;
        }
        return Float.parseFloat(data.replace(",", "."));
    }

}
